package com.qf.cloud2203.service2.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.cloud2203.domain.entity.Vote;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/service2")
public class Service2Controller {

    @Value("${server.port}")
    private Integer port;

    @GetMapping("/batch")
    public String testBatch() throws InterruptedException {

        final CountDownLatch latch = new CountDownLatch(6);

        for (int i=0;i<6;i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final RestTemplate restTemplate = new RestTemplate();
                    String url = "http://localhost:8091/service2/limit";
                    final String response = restTemplate.getForObject(url, String.class);
                    System.out.println(Thread.currentThread().getName()+":"+response);
                    latch.countDown();
                }
            }).start();
        }

        latch.await();
        System.out.println(Thread.currentThread().getName()+":所有线程任务结束");
        return "ok";
    }

    @GetMapping("/limit")
    @HystrixCommand(
            fallbackMethod = "fallback",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
            },
            threadPoolKey = "mypool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "3"),
                    @HystrixProperty(name = "maxQueueSize", value = "2")
            }
    )
    public String testLimitStream() throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        TimeUnit.SECONDS.sleep(1);
        return "test3 ok";
    }


    @HystrixCommand(fallbackMethod = "fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "70"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "5000")
    })
    @RequestMapping("/home")
    public String home(){
        System.out.println("=============================");

//        int a = 1/0;
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "service2home:"+port;
    }

    public String fallback(){
        return "服务不可用，返回fallback信息";
    }


    @GetMapping("/findAll")
    public List<Vote> getVoteList(){

        System.out.println(Thread.currentThread().getName());

        final ArrayList<Vote> votes = new ArrayList<>();

        final Vote vote1 = new Vote();
        vote1.setId(1);
        vote1.setPhone("13566667777");
        vote1.setCandidateId(1);
        vote1.setVoteNum(6);

        votes.add(vote1);
        votes.add(vote1);

        return votes;

    }

    @PostMapping("/update")
    Vote updateVote(@RequestBody Vote vote){
        vote.setVoteNum(100);
        return vote;
    }

    @DeleteMapping("/delete/{id}")
    Vote deleteVote(@PathVariable("id") Integer id){
        System.out.println("delete vote id="+id);
        final Vote vote = new Vote();
        vote.setId(-1);
        return vote;
    }

}
